package com.ying.service.system.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.startx.http.wordfilter.WordFilter;
import com.ying.core.exception.CustomException;
import com.ying.core.page.PageData;
import com.ying.core.page.PageWrap;
import com.ying.core.response.ResultCode;
import com.ying.core.utils.WordFilterUtil;
import com.ying.dao.system.UserRepository;
import com.ying.po.system.User;
import com.ying.service.system.UserService;
import me.zhyd.oauth.model.AuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


/**
 * 示例Service实现
 * @author 硬
 * @date 2021/12/04 20:13
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private WordFilterUtil wordFilterUtil;

    @Override
    public Integer create(User user) {
        if (user.getId() != null) {
            Optional<User> optional = userRepository.findById(user.getId());
            if (optional.isPresent()) {
                throw new CustomException(ResultCode.DATA_ALREADY_EXISTED, "UserServiceImpl.create");
            }
        }
        return userRepository.save(user).getId();
    }

    @Override
    public void deleteById(Integer id) {
        // 参数检验----------------------------------
        if (id == null)
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.deleteById");
        Optional<User> optional = userRepository.findById(id);
        if (!optional.isPresent()) {
            throw new CustomException(ResultCode.RESULE_DATA_NONE, "UserServiceImpl.deleteById");
        }
        // ------------开始业务----------------------
        User user = optional.get();
        user.setIsDelete(true);
        userRepository.save(user);
    }

    @Override
    public void deleteByIdInBatch(List<Integer> ids) {
        // 参数检验----------------------------------
        if (CollUtil.isEmpty(ids))
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.deleteByIdInBatch");
        // ------------开始业务----------------------
        for (Integer id: ids) {
            this.deleteById(id);
        }
    }

    @Override
    public void updateById(User user) {
        // -------------------参数检验---------------------
        if (user.getId() == null) {
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.updateById");
        }
        Optional<User> optional = userRepository.findById(user.getId());
        if (!optional.isPresent()) {
            throw new CustomException(ResultCode.RESULE_DATA_NONE, "UserServiceImpl.updateById");
        }
        // ------------开始业务----------------------
        Date updateTime = user.getUpdateTime();
//        DateUtil.format(updateTime, "yyyy");
        user.setUpdateTime(new Date());
        userRepository.save(user);
    }

    @Override
    public void updateByIdInBatch(List<User> users) {
        // ------------------参数检验---------------
        if (CollUtil.isEmpty(users))
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.updateByIdInBatch");
        // ------------开始业务----------------------
        for (User user: users) {
            this.updateById(user);
        }
    }

    @Override
    public User findById(Integer id) {
        // ------------------参数检验---------------
        if (id == null)
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.findById");
        // ------------开始业务----------------------
        Optional<User> optional = userRepository.findByIdAndIsNotDelete(id);
        if (!optional.isPresent()) {
            throw new CustomException(ResultCode.RESULE_DATA_NONE, "UserServiceImpl.findById");
        }
        return optional.get();
    }

    @Override
    public List<User> findByIdInBatch(List<Integer> ids) {
        // ------------------参数检验---------------
        if (CollUtil.isEmpty(ids))
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.findByIdInBatch");

        // ------------开始业务----------------------
        List<User> userList = new ArrayList<User>();
        for (Integer id : ids) {
            userList.add(this.findById(id));
        }
        return userList;
    }

    @Override
    public long countAll() {
        List<User> all = this.findAll();
        return all.size();
    }

    @Override
    public List<User> findAll() {
        return userRepository.findallisnotdelete();
    }

    @Override
    public PageData<User> queryAllByPage(PageWrap<User> pageWrap) {
        // ------------------参数检验---------------
        if (!pageWrap.check()) {
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.findPage");
        }
        // ------------开始业务----------------------
        Pageable pageable = PageRequest.of(pageWrap.getPage(), pageWrap.getCapacity(), pageWrap.sortMethod());
        User user = pageWrap.getModel();
        if (user.getStatus() == null && user.getUsername() == null) {
            Page<User> userPageIsNotDeleted = userRepository.getUserPageIsNotDeleted(pageable);
            return PageData.from(userPageIsNotDeleted);
        }
        if (user.getStatus() == null && user.getUsername() != null) {
            String username = user.getUsername();
            Page<User> pageByUsername = userRepository.findPageByUsername(pageable, username);
            return PageData.from(pageByUsername);
        }
        if (user.getStatus() != null && user.getUsername() == null) {
//            String username = user.getUsername();
            Integer status = user.getStatus();
            Page<User> pageByStatus = userRepository.findPageByStatus(pageable, status);
            return PageData.from(pageByStatus);
        }
        Integer status = user.getStatus();
        String username = user.getUsername();
        Page<User> pageByStatus = userRepository.findPageByStatusAndUsername(pageable, status, username);
        return PageData.from(pageByStatus);
    }

//    返回敏感词字段名
    @Override
    public boolean checkSensitiveWord(User user) {
        //      敏感词检验
        String username = user.getUsername() == null ? "" : user.getUsername();
        String nickname = user.getNickname() == null ? "" : user.getNickname();
        WordFilter wordFilter = wordFilterUtil.getWordFilter();
        return wordFilter.include(username) || wordFilter.include(nickname);
    }

    @Override
    public User findByUsernameAndPassword(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }

    @Override
    public Integer findByUserObj(User user) {
        Example<User> example = Example.of(user);
        Optional<User> one = userRepository.findOne(example);
        if (one.isPresent()) {
            return one.get().getId();
        }
        return null;
    }

    @Override
    public User getUserInfoFormAuthRes(AuthResponse authResponse) {

        JSONObject jsonObject = JSONUtil.parseObj(authResponse.getData());
        String username = jsonObject.getStr("username");
        String nickname = jsonObject.getStr("nickname");
        String avatar = jsonObject.getStr("avatar");
        String email = jsonObject.getStr("email");
        String sex = jsonObject.getStr("gender");
        String source = jsonObject.getStr("source");

        User user = new User();
        user.setUsername(username);
        user.setAvatar(avatar);
        user.setNickname(nickname);
        user.setStatus(1);
        user.setEmail(email);
        user.setSource(source);
        user.setType(0);
        user.setIsDelete(false);
        if (sex.equalsIgnoreCase("female")) {
            user.setSex(0);
        } else if (sex.equalsIgnoreCase("male")) {
            user.setSex(1);
        } else {
            user.setSex(null);
        }
        return user;
    }

    @Override
    public List<User> findByRoleCode(Integer roleCode) {
        return userRepository.findByRoleCode(roleCode);
    }

    @Override
    public PageData<User> findAllByPage(PageWrap pageWrap) {
        // ------------------参数检验---------------
        if (!pageWrap.check()) {
            throw new CustomException(ResultCode.PARAM_IS_BLANK, "UserServiceImpl.findPage");
        }
        // ------------开始业务----------------------
        Pageable pageable = PageRequest.of(pageWrap.getPage(), pageWrap.getCapacity(), pageWrap.sortMethod());
        Page<User> userPage = userRepository.getUserPageIsNotDeleted(pageable);
        PageData<User> pageData = PageData.from(userPage);
        return pageData;
    }

}
